package com.cdream.basic.mq.kafka;

import org.apache.kafka.common.serialization.Serializer;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author cdream
 * @date 2022/10/26
 */
public class DogSerializer implements Serializer<Dog> {
    @Override
    public void configure(Map<String, ?> configs, boolean isKey) {

    }

    @Override
    public byte[] serialize(String s, Dog dog) {
        if (dog == null) {
            return null;
        }
        try {
            byte[] name;
            if (dog.getName() == null) {
                name = new byte[0];
            } else {
                name = dog.getName().getBytes(StandardCharsets.UTF_8);
            }
            ByteBuffer buffer = ByteBuffer.allocate(4 + 4 + name.length + 4);
            buffer.putInt(name.length);
            buffer.put(name);
            buffer.putInt(4);
            buffer.putInt(dog.getAge());
            return buffer.array();
        } catch (Exception e) {
            e.printStackTrace();
        }


        return new byte[0];
    }


    @Override
    public void close() {

    }
}
